import 'package:flutter/material.dart';
import '../services/data_persistence_manager.dart';
import '../models/practice_task_model.dart';

/// 练习计划状态管理器
class PracticeScheduleProvider extends ChangeNotifier {
  final DataPersistenceManager _dataPersistenceManager;

  List<PracticeTaskModel> _practiceItems = [];
  TimeOfDay? _reminderTime;
  bool _isLoading = false;
  DateTime? _lastReminderDate;

  PracticeScheduleProvider(this._dataPersistenceManager) {
    _loadPracticeData();
  }

  /// Getters
  List<PracticeTaskModel> get practiceItems => _practiceItems;
  TimeOfDay? get reminderTime => _reminderTime;
  bool get isLoading => _isLoading;
  DateTime? get lastReminderDate => _lastReminderDate;

  /// 获取今日完成的任务数量
  int get completedTasksCount =>
      _practiceItems
          .where((task) => task.isCompleted && task.title.isNotEmpty)
          .length;

  /// 获取今日总任务数量（不包括空任务）
  int get totalTasksCount =>
      _practiceItems.where((task) => task.title.isNotEmpty).length;

  /// 获取完成进度百分比
  double get completionProgress {
    if (totalTasksCount == 0) return 0.0;
    return completedTasksCount / totalTasksCount;
  }

  /// 是否所有任务都已完成
  bool get isAllTasksCompleted =>
      totalTasksCount > 0 && completedTasksCount == totalTasksCount;

  /// 加载练习数据
  Future<void> _loadPracticeData() async {
    _setLoading(true);

    try {
      // 加载任务列表
      final tasksJson =
          _dataPersistenceManager.getStringList('practice_tasks') ?? [];
      _practiceItems =
          tasksJson
              .map((json) => PracticeTaskModel.fromJsonString(json))
              .toList();

      // 如果没有数据，初始化默认任务
      if (_practiceItems.isEmpty) {
        _initializeDefaultTasks();
      }

      // 加载提醒时间
      final reminderHour = _dataPersistenceManager.getInt('reminder_hour');
      final reminderMinute = _dataPersistenceManager.getInt('reminder_minute');
      if (reminderHour != null && reminderMinute != null) {
        _reminderTime = TimeOfDay(hour: reminderHour, minute: reminderMinute);
      }

      // 加载最后提醒日期
      final lastReminderTimestamp = _dataPersistenceManager.getInt(
        'last_reminder_date',
      );
      if (lastReminderTimestamp != null) {
        _lastReminderDate = DateTime.fromMillisecondsSinceEpoch(
          lastReminderTimestamp,
        );
      }

      // 检查是否需要重置每日任务状态
      _checkAndResetDailyTasks();
    } catch (e) {
      debugPrint('加载练习数据失败: $e');
    }

    _setLoading(false);
  }

  /// 初始化默认任务
  void _initializeDefaultTasks() {
    _practiceItems = [
      PracticeTaskModel(
        id: '1',
        title: 'Learn a New Chord',
        isCompleted: false,
      ),
      PracticeTaskModel(
        id: '2',
        title: 'Practice Ten Minutes of Finger Exercises',
        isCompleted: false,
      ),
      PracticeTaskModel(id: '3', title: '', isCompleted: false),
      PracticeTaskModel(id: '4', title: '', isCompleted: false),
      PracticeTaskModel(id: '5', title: '', isCompleted: false),
      PracticeTaskModel(id: '6', title: '', isCompleted: false),
      PracticeTaskModel(id: '7', title: '', isCompleted: false),
      PracticeTaskModel(id: '8', title: '', isCompleted: false),
    ];
  }

  /// 检查并重置每日任务状态
  void _checkAndResetDailyTasks() {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);

    // 获取上次更新日期
    final lastUpdateTimestamp = _dataPersistenceManager.getInt(
      'last_task_update',
    );
    DateTime? lastUpdateDate;
    if (lastUpdateTimestamp != null) {
      final lastUpdate = DateTime.fromMillisecondsSinceEpoch(
        lastUpdateTimestamp,
      );
      lastUpdateDate = DateTime(
        lastUpdate.year,
        lastUpdate.month,
        lastUpdate.day,
      );
    }

    // 如果是新的一天，重置所有任务的完成状态
    if (lastUpdateDate == null || lastUpdateDate.isBefore(today)) {
      for (var task in _practiceItems) {
        task.isCompleted = false;
      }
      _savePracticeData();
      _dataPersistenceManager.setInt(
        'last_task_update',
        now.millisecondsSinceEpoch,
      );
    }
  }

  /// 添加或更新任务
  Future<void> updateTask(int index, String title) async {
    if (index >= 0 && index < _practiceItems.length) {
      _practiceItems[index].title = title;
      _practiceItems[index].isCompleted = false;
      await _savePracticeData();
      notifyListeners();
    }
  }

  /// 切换任务完成状态
  Future<void> toggleTaskCompletion(int index) async {
    if (index >= 0 && index < _practiceItems.length) {
      _practiceItems[index].isCompleted = !_practiceItems[index].isCompleted;
      await _savePracticeData();
      notifyListeners();
    }
  }

  /// 设置提醒时间
  Future<void> setReminderTime(TimeOfDay time) async {
    _reminderTime = time;
    await _dataPersistenceManager.setInt('reminder_hour', time.hour);
    await _dataPersistenceManager.setInt('reminder_minute', time.minute);
    notifyListeners();
  }

  /// 清除提醒时间
  Future<void> clearReminderTime() async {
    _reminderTime = null;
    await _dataPersistenceManager.remove('reminder_hour');
    await _dataPersistenceManager.remove('reminder_minute');
    notifyListeners();
  }

  /// 记录提醒已显示
  Future<void> markReminderShown() async {
    _lastReminderDate = DateTime.now();
    await _dataPersistenceManager.setInt(
      'last_reminder_date',
      _lastReminderDate!.millisecondsSinceEpoch,
    );
  }

  /// 检查是否应该显示提醒
  bool shouldShowReminder() {
    if (_reminderTime == null) return false;

    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);

    // 检查今天是否已经显示过提醒
    if (_lastReminderDate != null) {
      final lastReminderDay = DateTime(
        _lastReminderDate!.year,
        _lastReminderDate!.month,
        _lastReminderDate!.day,
      );
      if (lastReminderDay.isAtSameMomentAs(today)) {
        return false; // 今天已经显示过提醒
      }
    }

    // 检查当前时间是否已过提醒时间
    final reminderDateTime = DateTime(
      now.year,
      now.month,
      now.day,
      _reminderTime!.hour,
      _reminderTime!.minute,
    );

    return now.isAfter(reminderDateTime) && !isAllTasksCompleted;
  }

  /// 重置所有任务
  Future<void> resetAllTasks() async {
    for (var task in _practiceItems) {
      task.isCompleted = false;
    }
    await _savePracticeData();
    notifyListeners();
  }

  /// 删除任务（清空内容）
  Future<void> clearTask(int index) async {
    if (index >= 0 && index < _practiceItems.length) {
      _practiceItems[index].title = '';
      _practiceItems[index].isCompleted = false;
      await _savePracticeData();
      notifyListeners();
    }
  }

  /// 保存练习数据
  Future<void> _savePracticeData() async {
    try {
      final tasksJson =
          _practiceItems.map((task) => task.toJsonString()).toList();
      await _dataPersistenceManager.setStringList('practice_tasks', tasksJson);
    } catch (e) {
      debugPrint('保存练习数据失败: $e');
    }
  }

  /// 设置加载状态
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  /// 刷新数据
  Future<void> refresh() async {
    await _loadPracticeData();
  }

  /// 获取任务统计信息
  Map<String, dynamic> getTaskStatistics() {
    return {
      'total': totalTasksCount,
      'completed': completedTasksCount,
      'remaining': totalTasksCount - completedTasksCount,
      'progress': completionProgress,
      'isAllCompleted': isAllTasksCompleted,
    };
  }
}
